package 尚硅谷.juc.test15;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
public class ShareData {

    private int number=0;
    private Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();

    /**
     * 自增
     */
    public  void increment() throws InterruptedException {

        try {
            lock.lock();

            //1：判断-阻塞
            while (number!=0){
                condition.await();
            }
            //2：干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //3：通知
            condition.signalAll();
        }catch (Exception exception){

        }finally {
            lock.unlock();
        }

    }

    /**
     * 自减
     */
    public  void decrement() throws InterruptedException {
       try {
           lock.lock();
           //1：判断-阻塞
           while (number==0){
               condition.await();
           }
           //2：干活
           number--;
           System.out.println(Thread.currentThread().getName()+"\t"+number);
           //3：通知
           condition.signalAll();
       }catch (Exception exception){

       }finally {
           lock.unlock();
       }
    }


}
